//
//  SearchSndViewController.m
//  Cook
//
//  Created by Macbookpro on 15/4/18.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "SearchSndViewController.h"
#import "DetailController.h"
#import "VegetableMenu.h"
#import "MyConnection.h"
#import "UIImageView+WebCache.h"
#import "UIScrollView+PullLoad.h"
#import "ResultCollectionViewCell.h"
#import "MONActivityIndicatorView.h"

@interface SearchSndViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, PullDelegate, UIAlertViewDelegate, MONActivityIndicatorViewDelegate>
{
    CGAdapter _myAd;
    UIAlertView *_fileAlertView;
    
}
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, assign) NSInteger addcount;

@property (nonatomic, retain) UIView *frontView;
@property (nonatomic, retain) NSTimer *netTimer;


@end

@implementation SearchSndViewController
- (void)dealloc
{
    [_dataArray release];
    [_title1 release];
    [_title2 release];
    [_dressArray release];
    [_collection release];
   
   
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArray = [NSMutableArray array];
        self.dressArray = [NSMutableArray array];
         _myAd = [AdapterModel getCGAdapter];
        _addcount = 0;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"搜索结果";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self creatBackground];
    [self creatCollection];
    [self creatLeftButton];
    [self createInvidate];
}

#pragma mark - 创建小菊花
- (void)createInvidate
{
    self.frontView = [[UIView alloc] initWithFrame:self.view.frame];
    _frontView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.2f];
    [self.view addSubview:_frontView];
    [_frontView release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification) name:@"frontView2" object:nil];
    
    MONActivityIndicatorView *indicator = [[MONActivityIndicatorView alloc] init];
    indicator.delegate = self;
    indicator.numberOfCircles = 3;
    indicator.radius = 20;
    indicator.internalSpacing = 3;
    indicator.center = _frontView.center;
    
    // 隐藏顶部navigationbar
    self.navigationController.navigationBar.hidden = YES;
    
    [indicator startAnimating];
    [_frontView addSubview:indicator];
    [indicator release];
    
    self.netTimer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(isHaveFront) userInfo:nil repeats:NO];
}


// 加载成功
- (void)notification
{
    [_netTimer invalidate];
    self.navigationController.navigationBar.hidden = NO;
    [self.frontView removeFromSuperview];
    self.frontView = nil;
}

// 判断加载情况
- (void)isHaveFront
{
    [_netTimer invalidate];
    if (_frontView != nil) {
        _fileAlertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        _fileAlertView.tag = 101;
        [_fileAlertView show];
    }
}


- (void)creatBackground
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"searchPhoto1.png"]];
    [self.view addSubview:imageView];
    [imageView release];
}

- (void)creatLeftButton
{
    UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    [self.view addSubview:bar];
    [bar release];
    [bar setBackgroundColor:[UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0]];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 40)];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    [bar addSubview:button];
    [button addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button release];
}

- (void)leftButtonAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 没有菜系返回
    if (alertView.tag == 101) {
    if (0 == buttonIndex) {
        [_netTimer invalidate];
        [self.frontView removeFromSuperview];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    }
    if (alertView.tag == 102) {
        if (0 == buttonIndex) {
            [_netTimer invalidate];
//            [self.frontView removeFromSuperview];
//            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    if (alertView.tag == 103) {
        [_netTimer invalidate];
        [self.frontView removeFromSuperview];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)creatCollection
{
    UICollectionViewFlowLayout *myLayout = [[UICollectionViewFlowLayout alloc] init];
    
    myLayout.itemSize = CGSizeMake(self.view.frame.size.width *0.5 - 20, 140 * _myAd.sHeight);
    myLayout.minimumInteritemSpacing = 5.0f;
    myLayout.minimumLineSpacing = 20.0f;
    myLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 20);
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:myLayout];
    [myLayout release];
    [_collection registerClass:[ResultCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _collection.backgroundColor = [UIColor clearColor];
    
    _collection.dataSource = self;
    _collection.delegate = self;
    
    // 设置代理人
    _collection.pullDelegate = self;
    // 允许程序上拉加载下拉刷新
    _collection.canPullUp = YES;
    
    [self.view addSubview:_collection];
    [_collection reloadData];
    [_collection release];
  
    [self scrollView:[[[UIScrollView alloc] init] autorelease] loadWithState:PullUpLoadState];
}

- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    self.count++;
    NSString *numTag = nil;
    for (NSString *num in self.dataArray) {
        if (numTag == nil) {
            numTag = num;
        }
        else {
            numTag = [NSString stringWithFormat:@"%@, %@", numTag, num];
        }
    }
    
    if (state == PullUpLoadState) {
        [self startConnect];
        self.navigationController.navigationBar.hidden = YES;
    }
    
}

- (void)startConnect
{
        NSString *str = [NSString stringWithFormat:@"%ld", self.count];
        NSString *url2 = [NSString stringWithFormat:@"%@%@%@", [_dressArray firstObject], str, [_dressArray lastObject]];
    
        __block SearchSndViewController *my = self;
        __block UICollectionView *myCollection = self.collection;
 
        [MyConnection connectWithUrl:[NSString stringWithFormat:@"%@", url2] parmaters:nil finishBlock:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic objectForKey:@"data"];
            if ([array count] != 0) {
                [my.dataArray addObjectsFromArray:array];
                my.addcount = 1;
                [myCollection reloadData];
                [myCollection stopLoadWithState:PullUpLoadState];
                my.navigationController.navigationBar.hidden = NO;
            } else {
                    NSString *message = [dic objectForKey:@"message"];
                if (([message isEqualToString:@"没有该条件组成的菜"]) && (my.addcount == 0)) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"抱歉亲，这里还没有您需求的菜系，去挑挑别的吧～" delegate:my cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alert.tag = 103;
                    [alert show];
                    [alert release];
                }
                else {
                    UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有更多的内容了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    view.tag = 102;
                    [view show];
                    [view release];
                    [myCollection setCanPullUp:NO];
                    [my.netTimer invalidate];
                    my.navigationController.navigationBar.hidden = NO;
                }
            }
            }];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_dataArray objectAtIndex:indexPath.item];
    ResultCollectionViewCell *cell = [_collection dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.foodImageView sd_setImageWithURL:[dic objectForKey:@"imagePathLandscape"] placeholderImage:image];
    [cell.foodNameLabel setText:[dic objectForKey:@"name"]];
    [cell.clickLabel setText:[NSString stringWithFormat:@"❤️ %@", [dic objectForKey:@"clickCount"]]];
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detail = [[[DetailController alloc] init] autorelease];
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.item];
    detail.vegetableMenuModel.vegetable_id = dic[@"vegetable_id"];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController pushViewController:detail animated:YES];

}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = [[collectionView indexPathsForVisibleItems] lastObject];
    if (my.row == indexPath.row) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"frontView2" object:nil];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
